package com.example.firstjavamqtt.service.log.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.firstjavamqtt.service.log.LedLogService;
import com.example.firstjavamqtt.common.excepiton.GlobalException;
import com.example.firstjavamqtt.common.result.ResultCodeEnum;
import com.example.firstjavamqtt.mapper.LedLogMapper;
import com.example.firstjavamqtt.model.device.Led;
import com.example.firstjavamqtt.model.log.LedLog;
import com.example.firstjavamqtt.utils.LogRequestUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

@Service
public class LedLogServiceImpl extends ServiceImpl<LedLogMapper, LedLog> implements LedLogService {

    //保存led
    public void saveLedLog(String string, HttpServletRequest request) {
        Led led = JSONObject.parseObject(string, Led.class);
        if (!led.isOnline()) {
            throw new GlobalException(ResultCodeEnum.OFFLINE);
        }
        LedLog ledLog = new LedLog();
        BeanUtils.copyProperties(led, ledLog);
        LogRequestUtil.setRequest(ledLog, request);

        //System.out.println(ledLog);

        baseMapper.insert(ledLog);
    }

    //删除某个id的LedLog
    @Override
    public void deleteLedLogById(int id) {
        int i = baseMapper.deleteById(id);
        if(i<1){
            throw new GlobalException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    //删除某个设备id的所有日志
    @Override
    public void deleteLedLogByDeviceId(String deviceId) {
        int i = baseMapper.delete(new QueryWrapper<LedLog>().eq("device_id", deviceId));
        if(i<1){
            throw new GlobalException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    @Override
    public void deleteLedLogByBatchId(ArrayList<Integer> batchId) {
        int i = baseMapper.deleteBatchIds(batchId);
        if(i<1){
            throw new GlobalException(ResultCodeEnum.PARAM_ERROR);
        }
    }

    @Override
    public Page<LedLog> getAllLedLog(int pageNum, int limit) {
        Page<LedLog> page = new Page<LedLog>(pageNum,limit);
        return baseMapper.selectPage(page,null);
    }


}
